/*
 *                    COPYRIGHT NOTICE
 *
 *           This code is copyright protected by Freedom Inc.
 *
 *              2001-2012 All Rights Are Reserved
 */
package com.freedom.oldsong.util;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import org.apache.log4j.Logger;

/**
 * @author steven.wang
 *
 */
public final class LanguageUtil {
	
	private static final Logger logger=Logger.getLogger(LanguageUtil.class);
	
	public static final String LANGUAGE = "LANGUAGE";
	public static final String CHINESE = "oldsong_zh_CN";
	public static final String ENGLISH = "oldsong_en_US";
	public static final String JAPANESE = "oldsong_jp_JP";
	
	private static Map<String ,Properties> languageMap = new HashMap<String ,Properties>();
	
	private LanguageUtil(){
		
	}
	
	static{
		loadProperties(CHINESE);
		loadProperties(ENGLISH);
		loadProperties(JAPANESE);
	}
	
	private static void loadProperties(String fileName){
		InputStream in = LanguageUtil.class.getResourceAsStream("/i18n/"+fileName+".properties");
		Properties p = new Properties();
		try {
			p.load(in);
		} catch (IOException e) {
			logger.error(e.getMessage());
		}
		languageMap.put(fileName, p);
	}
	
	public static String getText(String key, String language){
		String localLanguage=language;
		String localKey=key;
		if(localLanguage==null||languageMap.get(localLanguage)==null){
			localLanguage = ENGLISH;
		}
		try {
			if(localKey!=null){
				localKey = localKey.trim().replaceAll(" ", "_");
			}
			if(languageMap.get(localLanguage).get(localKey)!=null){
				return new String(((String)languageMap.get(localLanguage).get(localKey)).getBytes("ISO8859-1"),"UTF-8");
			}
		} catch (UnsupportedEncodingException e) {
			logger.error(e.getMessage());
		}
		return localKey.replaceAll("_", " ");
	}
}
